package com.thp.bigdata.inverIndex;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

/**
 * 倒排索引第二步
 * @author 汤小萌
 *
 */
public class InverIndexStepTwo {
	
	static class InverIndexStepTwoMapper extends Mapper<LongWritable, Text, Text, Text> {
		@Override
		protected void map(LongWritable key, Text value, Context context)
				throws IOException, InterruptedException {
			String line = value.toString();
			String[] fields = line.split("--");
			// String word = fields[0];
			// String fileAndNum = fields[1];
			/*context.write(new Text(word), // 单词
					new Text(fileAndNum.split("\t")[0] + " : "+fileAndNum.split("\t")[1] + "  ")); */ // 
			
			context.write(new Text(fields[0]), new Text(fields[1]));
		}
	}
	
	static class InverIndexStepTwoReducer extends Reducer<Text, Text, Text, Text> {
		@Override
		protected void reduce(Text key, Iterable<Text> values, Context context)
				throws IOException, InterruptedException {
			StringBuffer sb = new StringBuffer();
			for(Text value : values) {
				sb.append(value.toString().replaceAll("\t", "-->") + "\t");
			}
			context.write(key, new Text(sb.toString()));
		}
	}
	
	/**
	 * hello	c.txt-->2	b.txt-->2	a.txt-->3	
	   jerry	c.txt-->1	b.txt-->3	a.txt-->1	
	   tom	c.txt-->1	b.txt-->1	a.txt-->2	
	 * @param args
	 * @throws IOException
	 * @throws ClassNotFoundException
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		Configuration config = new Configuration();
		Job job = Job.getInstance(config);
		
		job.setJarByClass(InverIndexStepTwo.class);
		
		job.setMapperClass(InverIndexStepTwoMapper.class);
		job.setReducerClass(InverIndexStepTwoReducer.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		
		FileInputFormat.setInputPaths(job, new Path("F:/inverIndex/output_1"));
		FileOutputFormat.setOutputPath(job, new Path("F:/inverIndex/output_2"));
		
		System.exit(job.waitForCompletion(true) ? 0 : 1);
		
		
	}
	
}
